<template>
  <div class="user-profile">
    <!-- 导航栏 -->
    <van-nav-bar
    class="page-nav-bar"
    title="个人信息"
    left-arrow @click-left="$router.back()" />
    <!-- 图片上传 -->
    <input type="file" hidden ref="imgFile" @change="onChange">
    <!-- /导航栏 -->
    <van-cell title="头像" is-link @click="$refs.imgFile.click()" >
      <van-image
        class="avatar"
        fit="cover"
        round
        :src="user.photo"
      />
    </van-cell>
    <van-cell title="昵称" :value="user.name" is-link @click="isShowEdit=true" />
    <van-cell title="性别" :value="user.gender?'女':'男'" is-link @click="isShowEditSex=true" />
    <van-cell title="生日" :value="user.birthday" is-link @click="isShowEditBirthday=true" />

    <!-- 编辑昵称弹层 -->
    <van-popup v-model="isShowEdit" position="bottom" :style="{ height: '100%' }" >
      <user-edit @close="isShowEdit=false" v-model="user.name" />
    </van-popup>

    <!-- 编辑性别弹层 -->
    <van-popup v-model="isShowEditSex" position="bottom"  >
      <user-edit-sex @close="isShowEditSex=false" v-model="user.gender" />
    </van-popup>

    <!-- 编辑生日弹层 -->
    <van-popup v-model="isShowEditBirthday" position="bottom"  >
      <user-edit-birthday @close="isShowEditBirthday=false" v-model="user.birthday" />
    </van-popup>

    <!-- 编辑头像弹层 -->
    <van-popup v-model="isShowEditAvatar" position="bottom" :style="{ height: '100%' }" >
      <user-edit-avatar :img="imgUrl" @close="isShowEditAvatar=false" @avatar="user.photo=$event" />
    </van-popup>

  </div>
</template>

<script>
import { getUserProfile } from '@/api/user.js'
import UserEdit from './components/UserEdit.vue'
import UserEditSex from './components/UserEditSex.vue'
import UserEditBirthday from './components/UserEditBirthday.vue'
import UserEditAvatar from './components/UserEditAvatar.vue'
import { Toast } from 'vant'
export default {
  name: 'User',
  data () {
    return {
      user: {},
      isShowEdit: false,
      isShowEditSex: false,
      isShowEditBirthday: false,
      isShowEditAvatar: false,
      imgUrl: ''
    }
  },
  components: {
    UserEdit,
    UserEditSex,
    UserEditBirthday,
    UserEditAvatar
  },
  created () {
    this.getUserProfile()
  },

  methods: {
    // 头像编辑
    onChange (e) {
      if (e.target.value === '') return
      this.isShowEditAvatar = true
      this.imgUrl = URL.createObjectURL(e.target.files[0])
      e.target.value = ''
    },
    // 获取用户个人信息
    async getUserProfile () {
      Toast.loading({
        duration: 0,
        message: '加载中...',
        forbidClick: true
      })
      try {
        const res = await getUserProfile()
        this.user = res
        Toast.clear()
      } catch (err) {
        console.log(err)
        Toast.fail('获取信息失败！')
      }
    }
  }
}
</script>

<style scoped lang='less'>
.user-profile {
  .avatar {
    width: 60px;
    height: 60px;
  }
  /deep/.van-nav-bar__arrow {
    color: #fff;
  }
}
</style>
